﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.enums;
using InfonavaEye.handler;
using InfonavaEye.Handler;
using InfonavaEye.model;
using InfonavaEye.util;
using Sylan.Common.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace InfonavaEye.Forms
{
    public partial class BoxAreaForm : Form
    {
        FocusDistanceCurrentLimiter focusDistanceCurrentLimiter;

        /// <summary>
        /// 模式，1 添加，2修改,0 查看
        /// </summary>
        public int Mode { get; set; }

        /// <summary>
        /// 钉盒区域实体
        /// </summary>
        public BoxArea BoxArea { get; set; }

        /// <summary>
        /// 钉盒实体
        /// </summary>
        public BoxModel BoxModel { get; set; }

        /// <summary>
        /// 钉盒倾斜角度-x
        /// （左下角和右下角连成的线的角度）
        /// </summary>
        public double boxAngle = -9999;

        /// <summary>
        /// 钉盒倾斜角度-y
        /// （左上角和左下角连成的线的角度）
        /// </summary>
        public double boxAngleY = -9999;

        private bool timerStoped = false;
        System.Timers.Timer readLocationTimer;   // The auto exposure timer

        /// <summary>
        /// 默认坐标文本
        /// </summary>
        private string defaultXYZText = "0,0,0";

        /// <summary>
        /// 默认当前坐标
        /// </summary>
        private string defaultCurrentXYZText = "x,y,z";

        public event Action boxAreaCloseDelegate;

        private CameraHandler cameraHandler = CameraHandler.Instance;
        private PLCHandler plcHandler = PLCHandler.Instance;
        private LightHandler lightHandler = LightHandler.Instance;

        public BoxAreaForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
        }

        private void BoxAreaForm_Load(object sender, EventArgs e)
        {
            this.btnLeftDownLocation.DisabledForeColor = Color.Gray;
            this.btnLeftUpLocation.DisabledForeColor = Color.Gray;
            this.btnRightDownLocation.DisabledForeColor = Color.Gray;
            this.btnLeftDownLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.btnLeftUpLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.btnRightDownLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.lblCurrentXYZ.Text = defaultCurrentXYZText;
            this.panelFocusDistance.Visible = Config.DEVICE_MODEL == (int)DeviceModelEnum.A;
            int drawingBoxWidth = drawingBox.Width;
            drawingBox.Width = (int)(drawingBox.Height / 2048f * 3072f);
            drawingBox.Location = new Point(drawingBox.Location.X + (drawingBoxWidth - drawingBox.Width) / 2, drawingBox.Location.Y);

            //图像参考线
            this.initPicCursor();

            //光源亮度
            this.setLuminosity();

            #region 坐标计算
            this.btnLeftUpLocation.Visible = this.Mode > 0;
            this.btnLeftDownLocation.Visible = this.Mode > 0;
            this.btnRightDownLocation.Visible = this.Mode > 0;
            this.txtAreaName.Enabled = this.Mode > 0;
            this.numRowCount.Enabled = this.Mode > 0;
            this.numColumnCount.Enabled = this.Mode > 0;
            this.txtColumnTitle.Enabled = this.Mode > 0;
            this.btnSure.Text = this.Mode == 2 ? "修改" : "添加";
            this.lblLeftUpLocation.Text = defaultXYZText;
            this.lblRightDownLocation.Text = defaultXYZText;
            this.lblCurrentXYZ.Text = defaultCurrentXYZText;
            this.initForm();
            #endregion

            #region 相机调节
            try
            {
                this.focusDistanceTrackBar.Maximum = Config.CAMERA_FOCUS_DISTANCE_MAX;
                this.focusDistanceTrackBar.LargeChange = 100;
                lblFocusDistance.Text = Config.CAMERA_FOCUS_DISTANCE.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            #endregion


            ThreadHelper.ExcuteThreadTask(() =>
            {
                plcHandler.PLCInitCompleteDelegate += PLCHandler_PLCInitCompleteDelegate;
                focusDistanceCurrentLimiter = new FocusDistanceCurrentLimiter();
                plcHandler.StartPLC();
                cameraHandler.play(this.drawingBox);
            }, 250);
        }

        private void PLCHandler_PLCInitCompleteDelegate()
        {
            int[] xyz = plcHandler.readCurrentXYZ();
            try
            {
                if (xyz != null && xyz.Length >= 3)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.lblFocusDistance.Text = xyz[2].ToString();
                        this.focusDistanceTrackBar.Value = xyz[2];
                    }));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            InitAllTimers();

            this.Invoke(new Action(() =>
            {
                this.btnBack.Visible = true;
                this.btnSure.Visible = this.Mode > 0;
            }));
        }

        #region 图像参考线
        private void initPicCursor()
        {

            /*PictureBox xCrossLine = new PictureBox();
            PictureBox xCrossLine1 = new PictureBox();
            PictureBox xCrossLine2 = new PictureBox();
            PictureBox yCrossLine = new PictureBox();
            PictureBox yCrossLine1 = new PictureBox();
            PictureBox yCrossLine2 = new PictureBox();*/

            //圆型的最佳大小
            var marginTop = 40;
            var nailBestWidthOnView = drawingBox.Height - marginTop * 2;
            var nailBestHeightOnView = drawingBox.Height - marginTop * 2;
            var marginLeft = (drawingBox.Width - nailBestWidthOnView) / 2;

            xCrossLine.BackColor = System.Drawing.Color.Red;
            xCrossLine.TabStop = false;
            xCrossLine.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine.Height = 1;
            xCrossLine.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + marginTop);

            xCrossLine1.BackColor = System.Drawing.Color.Red;
            xCrossLine1.TabStop = false;
            xCrossLine1.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine1.Height = 1;
            xCrossLine1.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + drawingBox.Height / 2);

            xCrossLine2.BackColor = System.Drawing.Color.Red;
            xCrossLine2.TabStop = false;
            xCrossLine2.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine2.Height = 1;
            xCrossLine2.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + drawingBox.Height - marginTop);

            ////Y
            yCrossLine.BackColor = System.Drawing.Color.Red;
            yCrossLine.TabStop = false;
            yCrossLine.Width = 1;
            yCrossLine.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine.Location = new Point(drawingBox.Location.X + (drawingBox.Width - nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop);

            yCrossLine1.BackColor = System.Drawing.Color.Red;
            yCrossLine1.TabStop = false;
            yCrossLine1.Width = 1;
            yCrossLine1.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine1.Location = new Point(drawingBox.Location.X + drawingBox.Width / 2, drawingBox.Location.Y + marginTop);

            yCrossLine2.BackColor = System.Drawing.Color.Red;
            yCrossLine2.TabStop = false;
            yCrossLine2.Width = 1;
            yCrossLine2.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine2.Location = new Point(drawingBox.Location.X + (drawingBox.Width + nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop);

            /*this.Controls.Add(xCrossLine);
            this.Controls.Add(xCrossLine1);
            this.Controls.Add(xCrossLine2);
            this.Controls.Add(yCrossLine);
            this.Controls.Add(yCrossLine1);
            this.Controls.Add(yCrossLine2);*/

            /* xCrossLine.Visible = false;
             yCrossLine.Visible = false;*/
        }
        #endregion

        private void BoxAreaForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            plcHandler.PLCInitCompleteDelegate -= PLCHandler_PLCInitCompleteDelegate;
            this.cameraHandler.pause();//暂停视频
            if (readLocationTimer != null)
            {
                timerStoped = true;
                readLocationTimer.Stop();
                readLocationTimer.Close();
            }
            if (boxAreaCloseDelegate != null)
            {
                boxAreaCloseDelegate.Invoke();
            }
        }

        /// <summary>
        /// 设置光源
        /// </summary>
        private int[] lightItems = Config.LIGHT_SOURCE_LUMINOSITY_ITEMS.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
        private void setLuminosity()
        {
            if (this.BoxModel == null) return;

            if (lightItems.Length >= 3)
            {
                this.radioLuminosity1.Checked = (this.BoxModel.LightLuminosity == lightItems[0]);
                this.radioLuminosity2.Checked = (this.BoxModel.LightLuminosity == lightItems[1]);
                this.radioLuminosity3.Checked = (this.BoxModel.LightLuminosity == lightItems[2]);
            }
            if (this.BoxModel.LightLuminosity == 0)
            {
                this.radioLuminosity1.Checked = true;
                this.BoxModel.LightLuminosity = lightItems[0];
            }
            lightHandler.ChangeLuminance(this.BoxModel.LightLuminosity);
        }

        bool closing = false;
        protected override void OnClosing(CancelEventArgs e)
        {
            if (cameraHandler.isCameraOpening)
            {
                e.Cancel = true; //取消关闭操作
                MessageBox.Show("相机正在连接中，无法中断，请稍后再尝试关闭", "提示", MessageBoxButtons.OK);
                return;
            }

            closing = true;
        }

        /// <summary>
        /// 初始化表单
        /// </summary>
        private void initForm()
        {
            if (this.Mode == 1)
            {
                this.BoxArea = new BoxArea() { code = Guid.NewGuid().ToString("N") };
            }
            else
            {
                if (this.BoxArea == null)
                {
                    AutoCloseMessageBox.Show("未找到区域的数据");
                    return;
                }
                this.txtAreaName.Text = this.BoxArea.name;
                this.numColumnCount.Value = this.BoxArea.columnCount;
                this.numRowCount.Value = this.BoxArea.rowCount;
                this.txtColumnTitle.Text = String.Join(",", this.BoxArea.columnTitle);
                if (this.boxAngle != -9999)
                {
                    this.lblBoxAngle.Text = this.boxAngle.ToString();
                }
                this.parseAreaXYZ();
            }
        }

        /// <summary>
        /// 计算区域4个角的坐标
        /// </summary>
        private void parseAreaXYZ()
        {
            var rowCount = this.BoxArea.rowCount;
            var columnCount = this.BoxArea.columnCount;
            var startPoint = this.BoxArea.startPoint;
            var holdPitch = this.BoxArea.holdPitch;
            if (startPoint == null || rowCount == 0 || columnCount == 0 || holdPitch == null)
            {
                return;
            }

            var x = startPoint[0];
            var y = startPoint[1];
            var z = startPoint[2];
            var xPitch = holdPitch[0];
            var yPitch = holdPitch[1];

            var rightDownPoint = new int[] { x, y, z };
            this.lblRightDownLocation.Text = String.Join(",", rightDownPoint);

            if (this.boxAngle != -9999)
            {
                //以右下角为基础点，计算左下角。
                var leftDownPoint = new int[] {
                    (int)(x + xPitch * (columnCount - 1) * Math.Cos(this.boxAngle * Math.PI / 180)),
                    (int)(y + xPitch * (columnCount - 1) * Math.Sin(this.boxAngle * Math.PI / 180)),
                    z,
                };
                this.lblLeftDownLocation.Text = String.Join(",", leftDownPoint);

                //以左下角为基础点，计算左上角
                var leftUpPoint = new int[] {
                    (int)(leftDownPoint[0] + yPitch * (rowCount - 1)* Math.Cos((90-this.boxAngle)* Math.PI / 180)),
                    (int)(leftDownPoint[1] + yPitch * (rowCount - 1)* Math.Sin((90-this.boxAngle) *Math.PI / 180)),
                    z,
                };
                this.lblLeftUpLocation.Text = String.Join(",", leftUpPoint);
            }
        }

        private void InitAllTimers()
        {
            readLocationTimer = new System.Timers.Timer(100);
            readLocationTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerReadLocation);
            readLocationTimer.AutoReset = true;
            readLocationTimer.SynchronizingObject = this;
            readLocationTimer.Start();
        }

        private void OnTimerReadLocation(object sender, ElapsedEventArgs e)
        {
            readLocationTimer.Stop();
            this.readXYZ();
            if (!timerStoped)
            {
                readLocationTimer.Start();
            }
        }
        private int[] readXYZ()
        {
            try
            {
                Console.WriteLine("readXYZ BoxAreaForm");
                int[] xyz = plcHandler.readCurrentXYZ();// new int[] { 200, 300, 500 };// 
                lblCurrentXYZ.Text = String.Format("{0},{1},{2}", xyz[0], xyz[1], xyz[2]);
                Console.WriteLine("读取到当前坐标：{0}", lblCurrentXYZ.Text);
                return xyz;
            }
            catch (Exception ex)
            {
                AutoCloseMessageBox.Show(ex.Message);
                return null;
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtAreaName.Text))
            {
                AutoCloseMessageBox.Show("请输入区域名称");
                return;
            }
            if (this.numRowCount.Value == 0)
            {
                AutoCloseMessageBox.Show("请输入区域行数");
                return;
            }
            if (this.numColumnCount.Value == 0)
            {
                AutoCloseMessageBox.Show("请输入区域列数");
                return;
            }
            if (String.IsNullOrEmpty(this.txtColumnTitle.Text))
            {
                AutoCloseMessageBox.Show("请输入列标识");
                return;
            }
            if (defaultXYZText.Equals(this.lblLeftUpLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左上上位置的坐标");
                return;
            }
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域右下位置的坐标");
                return;
            }
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左下位置的坐标");
                return;
            }
            if (this.boxAngle == -9999)
            {
                AutoCloseMessageBox.Show("请先填入区域3个位置的坐标，自动计算出钉盒倾斜角度");
                return;
            }

            this.BoxArea.name = this.txtAreaName.Text;
            this.BoxArea.rowCount = (int)this.numRowCount.Value;
            this.BoxArea.columnCount = (int)this.numColumnCount.Value;
            this.BoxArea.columnTitle = this.txtColumnTitle.Text.Split(new char[] { ',', '，', ' ' });
            //测试数据
            /* this.lblRightDownLocation.Text = "1056,-1580,6901";
             this.lblLeftDownLocation.Text = "17182,-1510,6901";
             this.lblLeftUpLocation.Text = "17182,198,6901";*/
            this.calcBoxAngle();
            if (this.calcAreaXYZ())
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private bool calcAreaXYZ()
        {
            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3 || leftUpPoint.Length < 3 || leftDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域位置坐标数据不正常");
                return false;
            }
            var xPitch = 0;
            if (this.BoxArea.columnCount > 1)
            {
                xPitch = (int)MathUtil.calcDistance((double)rightDownPoint[0], (double)rightDownPoint[1],
                    (double)leftDownPoint[0], (double)leftDownPoint[1]) / (this.BoxArea.columnCount - 1);
            }

            var yPitch = 0;
            if (this.BoxArea.rowCount > 1)
            {
                yPitch = (int)MathUtil.calcDistance((double)leftUpPoint[0], (double)leftUpPoint[1],
                    (double)leftDownPoint[0], (double)leftDownPoint[1]) / (this.BoxArea.rowCount - 1);
            }

            if (xPitch < 0 || yPitch < 0)
            {
                AutoCloseMessageBox.Show("区域坐标计算出的孔距不正常");
                return false;
            }
            this.BoxArea.holdPitch = new int[] { xPitch, yPitch };
            this.BoxArea.startPoint = rightDownPoint;
            return true;
        }

        private void drawingBox_Paint(object sender, PaintEventArgs e)
        {
            PictureBox p = (PictureBox)sender;
            Pen pp = new Pen(Color.FromArgb(255, 0, 77, 203));
            e.Graphics.DrawRectangle(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - 1, e.ClipRectangle.Y + e.ClipRectangle.Height - 1);
        }

        private void btnLeftUpLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblLeftUpLocation.Text = this.lblCurrentXYZ.Text;
            }
        }

        private void btnRIghtDownLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblRightDownLocation.Text = this.lblCurrentXYZ.Text;
                this.calcBoxAngle();
            }
        }

        private void btnLeftDownLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblLeftDownLocation.Text = this.lblCurrentXYZ.Text;
                this.calcBoxAngle();
            }
        }

        private void calcBoxAngle()
        {
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                return;
            }
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                return;
            }

            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            //var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3 || leftDownPoint.Length < 3)
            {
                return;
            }

            this.boxAngle = MathUtil.anglevalue(rightDownPoint[0], rightDownPoint[1], leftDownPoint[0], leftDownPoint[1]);//校准前的对角线的角度
            this.boxAngle = Math.Round(this.boxAngle, 8, MidpointRounding.AwayFromZero);//保留8位小数
            this.lblBoxAngle.Text = this.boxAngle.ToString();

            //this.boxAngleY = MathUtil.anglevalue(leftDownPoint[0], leftDownPoint[1], leftUpPoint[0], leftUpPoint[1]);//校准前的对角线的角度
            //this.boxAngleY = Math.Round(this.boxAngleY, 8, MidpointRounding.AwayFromZero);//保留8位小数
            //this.lblBoxAngle.Text = this.boxAngle.ToString();
        }

        private bool checkCurrentXYZ()
        {
            if (defaultCurrentXYZText.Equals(this.lblCurrentXYZ.Text))
            {
                AutoCloseMessageBox.Show("当前坐标没有数据");
                return false;
            }
            return true;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnLeftUpLocate_Click(object sender, EventArgs e)
        {
            if (defaultXYZText.Equals(this.lblLeftUpLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左上位置的坐标");
                return;
            }
            var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (leftUpPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域左上位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(1);
            this.moveToPoint(leftUpPoint);
        }

        private void btnLeftDownLocate_Click(object sender, EventArgs e)
        {
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左下位置的坐标");
                return;
            }
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (leftDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域左下位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(2);
            this.moveToPoint(leftDownPoint);
        }

        private void btnRightDownLocate_Click(object sender, EventArgs e)
        {
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域右下位置的坐标");
                return;
            }
            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域右下位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(3);
            this.moveToPoint(rightDownPoint);
        }

        bool moving = false;
        private void moveToPoint(int[] point)
        {
            if (point == null || point.Length == 0)
            {
                AutoCloseMessageBox.Show("坐标不正确");
                return;
            }

            if (moving) return;

            ThreadHelper.ExcuteThreadTask(() =>
            {
                timerStoped = true;
                readLocationTimer.Stop();
                btnSure.Enabled = false;
                btnSure.Text = "移动中";
                try
                {
                    plcHandler.moveToXYZandCapture(point[0], point[1], point[2], false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    moving = false;
                    timerStoped = false;
                    readLocationTimer.Start();
                    btnSure.Enabled = true;
                    this.btnSure.Text = this.Mode == 2 ? "修改" : "添加";
                    toggleButtonStatus(0);
                }
            });
        }

        /// <summary>
        /// 切换按钮状态(参数 what : 1 左上，2.左下，3.右下,0.没有按下按钮)
        /// </summary>
        /// <param name="what"> 1 左上，2.左下，3.右下,0.没有按下按钮</param>
        private void toggleButtonStatus(int what)
        {
            this.btnLeftUpLocate.Enabled = what == 0;
            this.btnLeftUpLocate.Text = what == 1 ? "移动中" : "移动到这个点";

            this.btnLeftDownLocate.Enabled = what == 0;
            this.btnLeftDownLocate.Text = what == 2 ? "移动中" : "移动到这个点";

            this.btnRightDownLocate.Enabled = what == 0;
            this.btnRightDownLocate.Text = what == 3 ? "移动中" : "移动到这个点";

            this.btnRightDownLocation.Enabled = what == 0;
            this.btnLeftDownLocation.Enabled = what == 0;
            this.btnLeftUpLocation.Enabled = what == 0;
        }

        private void btnFocusDistanceMinus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                if (focusDistanceTrackBar.Value > 10)
                {
                    focusDistanceTrackBar.Value -= 10;
                    this.changeFocusDistance();
                }
            }));
        }

        private void btnFocusDistancePlus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                focusDistanceTrackBar.Value += 10;
                this.changeFocusDistance();
            }));
        }

        private void changeFocusDistance()
        {
            lblFocusDistance.Text = focusDistanceTrackBar.Value.ToString();
            focusDistanceCurrentLimiter.adjust(focusDistanceTrackBar.Value);
        }



        /// <summary>
        /// 焦距调节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void focusDistanceTrackBar_Scroll(object sender, EventArgs e)
        {
            lblFocusDistance.Text = focusDistanceTrackBar.Value.ToString();
        }

        private void focusDistanceTrackBar_MouseUp(object sender, MouseEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.changeFocusDistance();
            }));
        }

        private void btnRefreshPic_Click(object sender, EventArgs e)
        {
            ThreadHelper.ExcuteThreadTask(() =>
            {
                this.cameraHandler.play(this.drawingBox);
            });
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        /// <summary>
        /// 获取光源亮度（1,2,3 三档）
        /// </summary>
        /// <returns></returns>
        private int getLuminosity()
        {
            if (lightItems.Length >= 3)
            {
                if (this.radioLuminosity1.Checked)
                {
                    return lightItems[0];
                }
                else if (this.radioLuminosity2.Checked)
                {
                    return lightItems[1];
                }
                else
                {
                    return lightItems[2];
                }
            }
            return Config.LIGHT_SOURCE_LUMINOSITY_DEFAULT;
        }

        //改变光源亮度
        private void radioLuminosity1_CheckedChanged(object sender, EventArgs e)
        {
            int luminosity = getLuminosity();
            this.BoxModel.LightLuminosity = luminosity;
            lightHandler.ChangeLuminance(luminosity);
        }
    }
}
